package com.guli.shop.config;
/*
 * @Author 罗俊
 * @date 2020/12/7 - 10:23 下午
 *
 */

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@Configuration
@Slf4j
public class SentinelGatewayConfig {

    public SentinelGatewayConfig() {

        log.info("正在设置网关限流回调处理器");

        GatewayCallbackManager.setBlockHandler((ServerWebExchange var1, Throwable var2) -> {

            // Mono Flux 都是 spring 5 的 新特性，响应式编程
            log.warn("网关限流了");

            HashMap<String, String> map = new HashMap<>();

            map.put("code","998");

            map.put("msg","太多请求，网关顶不住了");

            String errorJson = JSON.toJSONString(map);

            Mono<String> just = Mono.just(errorJson);

            Mono<ServerResponse> body = ServerResponse.ok().body(just, String.class);

            return body;
        });
    }
}
